<script setup>
import { onMounted, ref ,watch} from 'vue'
import { queryPageApi, addApi, queryInfoApi, updateApi, deleteApi } from '@/api/subject'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryAllApi as queryAllEmpApi } from '@/api/emp'
import { queryAllApi as queryAllDeptApi } from '@/api/dept'

//所有的员工数据
let emps = ref([])
//加载所有的员工数据
const queryAllEmp = async () => {
  let result = await queryAllEmpApi()
  if (result.code) {
    emps.value = result.data
  }
}
//所有的部门数据
let depts = ref([])
//加载所有的部门数据
const queryAllDept = async () => {
  let result = await queryAllDeptApi()
  if (result.code) {
    depts.value = result.data
  }
}

// 搜索表单对象
let searchSubject = ref({ name: '' })
// 列表数据
let tableData = ref([])

// 分页配置
const pagination = ref({ currentPage: 1, pageSize: 10, total: 0 })

// 初始化加载数据
onMounted(() => {
  queryPage()
  queryAllEmp()
  queryAllDept()
})

// 分页查询
const queryPage = async () => {
  const result = await queryPageApi(
    searchSubject.value.name,
    pagination.value.currentPage,
    pagination.value.pageSize
  )
  
  if (result.code) {
    tableData.value = result.data.rows
    pagination.value.total = result.data.total
  }
}

// 分页事件处理
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize
  queryPage()
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  queryPage()
}

// 清空搜索
const clear = () => {
  searchSubject.value = { name: '' }
  queryPage()
}

// ----------- 新增/编辑 -----------
let dialogFormVisible = ref(false)
let formTitle = ref('')
let subject = ref({ moduleNo: '', moduleName: '', departmentNo: '' ,moduleCoordinatorEmpNo: '',semesterDisponivel:'' ,departmentName:'',empName:'' })

// 表单校验规则
const subjectFormRef = ref()
const rules = ref({
  name: [
    { required: true, message: '学科名称为必填项', trigger: 'blur' },
    { min: 2, max: 30, message: '名称长度为2-30个字符', trigger: 'blur' }
  ]
})

const clearSubject = () => {
 subject.value = { moduleNo: '', moduleName: '', departmentNo: '' ,moduleCoordinatorEmpNo: '',semesterDisponivel:'' ,departmentName:'',empName:'' }
}
// 打开新增弹窗
const addSubject = () => {
  dialogFormVisible.value = true
  formTitle.value = '新增学科'
  clearSubject()
}

// 打开编辑弹窗
const updateSubject = async (id) => {
  clearSubject()
  const result = await queryInfoApi(id)
  if (result.code) {
    subject.value = result.data
    dialogFormVisible.value = true
    formTitle.value = '编辑学科'
  }
}

// 保存数据
const save = async (subjectForm) => {
  if(!subjectForm)return
  subjectForm.validate(async (valid) => {
    if (valid) {
      let api
      if (subject.value.moduleNo) {
        api = updateApi(subject.value)
      } else {
        api = addApi(subject.value)
      }
      let result = await api
      if (result.code) {
        ElMessage.success('操作成功')
        dialogFormVisible.value = false
        queryPage()
      }else{
        ElMessage.error(ref.msg)
      }
    }else{
      return false
    }
  })
}

// 删除学科
const delById = (id) => {
  ElMessageBox.confirm('确认删除该学科吗？', '警告', { type: 'warning' })
    .then(async () => {
      const result = await deleteApi(id)
      if (result.code) {
        ElMessage.success('删除成功')
        queryPage()
      }
    })
    .catch(() => ElMessage.info('已取消'))
}
</script>

<template>
  <!-- 标题 -->
  <div id="title">学科管理</div>
  <br>

  <!-- 搜索表单 -->
  <el-form :inline="true">
    <el-form-item label="学科名称">
      <el-input v-model="searchSubject.name" placeholder="请输入名称"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="queryPage">查询</el-button>
      <el-button @click="clear">重置</el-button>
    </el-form-item>
  </el-form>

  <!-- 操作按钮 -->
  <el-button type="success" @click="addSubject">+ 新增学科</el-button>
  <br><br>

  <!-- 数据表格 -->
  <el-table :data="tableData" border>
    <el-table-column type="index" label="序号" width="100"/>
    <el-table-column prop="moduleName" label="学科名称" width="160"/>
    <el-table-column prop="empName" label="主讲教师" width="160"/>
    <el-table-column prop="departmentName" label="所属部门" width="160"/>
    <el-table-column label="操作" width="150">
      <template #default="{ row }">
        <el-button type="primary" size="small" @click="updateSubject(row.moduleNo)">编辑</el-button>
        <el-button type="danger" size="small" @click="delById(row.moduleNo)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    v-model:current-page="pagination.currentPage"
    v-model:page-size="pagination.pageSize"
    :page-sizes="[5, 10, 20, 50]"
    layout="total, sizes, prev, pager, next"
    :total="pagination.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!-- 表单弹窗 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="500px">
    <el-form ref="subjectFormRef" :model="subject" :rules="rules">
      <el-form-item label="名称" prop="moduleName" label-width="80px">
        <el-input v-model="subject.moduleName" placeholder="请输入学科名称"/>
      </el-form-item>

      <el-form-item label="开课时间" prop="semesterDisponivel" label-width="80px">
        <el-input v-model="subject.semesterDisponivel" placeholder="请输入时间"/>
      </el-form-item>

      <el-form-item label="讲师" :label-width="labelWidth">
        <el-select v-model="subject.moduleCoordinatorEmpNo" placeholder="请选择讲师" style="width: 100%;">
          <el-option v-for="emp in emps" :label="emp.name" :value="emp.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="部门" :label-width="labelWidth">
        <el-select v-model="subject.departmentNo" placeholder="请选择部门" style="width: 100%;">
          <el-option v-for="dept in depts" :label="dept.name" :value="dept.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="save(subjectFormRef)">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
#title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}
</style>